import {View, TouchableOpacity, Text, ToastAndroid, StyleSheet, ActivityIndicator, AlarmManager} from 'react-native';
import * as TaskManager from 'expo-task-manager';
import * as BackgroundFetch from 'expo-background-fetch';
import BackgroundTimer from 'react-native-background-timer';
import {
  requestPermissions, // 请求设备权限
  connectToDeviceByDeviceId, // 连接设备通过 id
  disconnectDevice, // 断开连接
  updateBikeStatus,
  monitorDisConnect,
  isDeviceConnectedByDeviceId
} from '@/utils/ble';
import {useEffect, useRef, useState} from 'react';
import { Characteristic } from 'react-native-ble-plx';
import { BluetoothCtrlBikeCommandEnum, BluetoothStatusTypeEnum } from '@/constants/BluetoothEnum';
import IconButton from '@/components/IconButton';

const BLUETOOTH_BLUETOOTH_TASK_NAME = 'background-bluetooth-task';

// const deviceId:string = 'CA:B9:4A:4B:0A:9F' // 我的车辆
const deviceId:string = 'D2:EB:0D:9E:85:59'
let reconnectTimer:any = null

// 这个方法不能写在 component内部
TaskManager.defineTask(BLUETOOTH_BLUETOOTH_TASK_NAME, async () => {
  // 这里执行你的后台任务，比如更新计时器状态
  const now = Date.now();
  console.log(`Got background fetch call at date: ${new Date(now).toUTCString()}`);
  gConnectBike()
  // Be sure to return the successful result type!
  return BackgroundFetch.BackgroundFetchResult.NewData;
});
// 注册一个后台任务
async function registerBackgroundFetchBluetoothAsync() {
  gonDisconnect()
  console.log('注册一个后台任务')
  return BackgroundFetch.registerTaskAsync(BLUETOOTH_BLUETOOTH_TASK_NAME, {
    minimumInterval: 60 * 1, // 执行频率
    stopOnTerminate: false, // android only,
    startOnBoot: true, // android only
  });
}

// 注销后台任务
async function unregisterBackgroundFetchBluetoothAsync() {
  return BackgroundFetch.unregisterTaskAsync(BLUETOOTH_BLUETOOTH_TASK_NAME);
}

// 监听连接断开
function gonDisconnect() {
  monitorDisConnect(deviceId, (err) => {
    console.log('连接断开1')
  })
}

function gConnectBike() {
  // 是否处于连接状态
  isDeviceConnectedByDeviceId(deviceId, (status: boolean) => {
    if(status) {
      return
    }
    const now = Date.now();
    console.log(`开始连接${new Date(now).toUTCString()}`)
    // 连接蓝牙
    connectToDeviceByDeviceId(deviceId, (flag: boolean, characteristic: Characteristic) => {
      if(flag) {
        console.log(`连接成功`);
      } else {
        console.log('连接断开0')
      }
    })
  })
}

// 设置一个计时器定时连接
// function gtoReconnect() {
//   if(reconnectTimer) {
//     BackgroundTimer.clearTimeout(reconnectTimer)
//   }
//   reconnectTimer = BackgroundTimer.setTimeout(() => {
//     gConnectBike()
//   }, 10 * 1000)
// }

export default function App() {
  const [isRegistered, setIsRegistered] = useState(false); // 是否注册后台任务
  const [status, setStatus] = useState(null);
  
  useEffect(() => {
    checkStatusAsync();
  }, []);

  const checkStatusAsync = async () => {
    const status = await BackgroundFetch.getStatusAsync();
    const isRegistered = await TaskManager.isTaskRegisteredAsync(BLUETOOTH_BLUETOOTH_TASK_NAME);
    setStatus(status);
    setIsRegistered(isRegistered);
  };

  const toggleFetchTask = async () => {
    if (isRegistered) {
      await unregisterBackgroundFetchBluetoothAsync();
    } else {
      await registerBackgroundFetchBluetoothAsync();
    }

    checkStatusAsync();
  };
  return (
      <View>
        <View style={styles.screen}>
          <View style={styles.textContainer}>
            <Text>
              Background fetch status:{' '}
              <Text style={styles.boldText}>
                {status && BackgroundFetch.BackgroundFetchStatus[status]}
              </Text>
            </Text>
            <Text>
              Background fetch task name:{' '}
              <Text style={styles.boldText}>
                {isRegistered ? BLUETOOTH_BLUETOOTH_TASK_NAME : 'Not registered yet!'}
              </Text>
            </Text>
          </View>
          <View style={styles.textContainer}></View>
          <View style={styles.btnBox}>
            <IconButton icon='check' label={isRegistered ? 'Unregister BackgroundFetch task' : 'Register BackgroundFetch task'} onPress={toggleFetchTask} />
          </View>
        </View>
      </View>
    );
  }
  
  
  const styles = StyleSheet.create({
    btnBox: {
      marginBottom: 20
    },
    screen: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    textContainer: {
      margin: 10,
    },
    boldText: {
      fontWeight: 'bold',
    },
  })

function dayjs() {
  throw new Error('Function not implemented.');
}
